const S3 = require('aws-sdk/clients/s3')
const multer = require('multer')
const multerS3 = require('multer-s3')
const generateRandomHash = require('../generateRandomHash')
const ResponseError = require('../ResponseError')
const {
  AWS_ACCESS_KEY_ID,
  AWS_SECRET_KEY,
  AWS_S3_BUCKET,
} = require('../../config')

const s3 = new S3({
  accessKeyId: AWS_ACCESS_KEY_ID,
  secretAccessKey: AWS_SECRET_KEY,
})

const imageUploader = multer({
  storage: multerS3({
    s3,
    bucket: AWS_S3_BUCKET,
    // metadata: (req, file, cb) => {
    //   console.log('file', file)
    //   cb(null, { fieldName: file.fieldname })
    // },
    key: (req, file, cb) => {
      // const file = {
      //   fieldname: 'file',
      //   originalname: 'logo.png',
      //   encoding: '7bit',
      //   mimetype: 'image/png'
      // }
      if (!file || file.fieldname !== 'file') {
        const error = new ResponseError.ParameterRequired()
        error.field = 'file'
        cb(error)
      }
      const fullNameWithExtension = file.originalname
      const parts = fullNameWithExtension.split('.')
      const extension = parts.splice(-1, 1)[0]
      const name = parts.join('.')
      if (!extension.toLowerCase().match(/(jpg|jpeg|png)$/i)) {
        const error = new ResponseError.ValidationError()
        error.message = 'Please upload file in format png, jpg, jpeg only.'
        cb(error)
      }
      const hash = generateRandomHash(8)
      const uploadName = `${name}.${hash}.${extension}`
      cb(null, uploadName)
    },
  }),
  limits: { fileSize: 1048576 }, // in byte 1048576 = 1mb
})

const documentUploader = multer({
  storage: multerS3({
    s3,
    bucket: AWS_S3_BUCKET,
    key: (req, file, cb) => {
      // const file = {
      //   fieldname: 'file',
      //   originalname: 'logo-app.png',
      //   encoding: '7bit',
      //   mimetype: 'image/png'
      // }
      if (!file) {
        cb(new ResponseError.ParameterRequired())
      }
      const fullNameWithExtension = file.originalname
      const parts = fullNameWithExtension.split('.')
      const extension = parts.splice(-1, 1)[0]
      const name = parts.join('.')
      if (!extension.toLowerCase().match(/(pdf)$/i)) {
        cb(new ResponseError.ValidationError())
      }
      const hash = generateRandomHash(8)
      const uploadName = `${name}.${hash}.${extension}`
      cb(null, uploadName)
    },
    limits: { fileSize: 1048576 }, // in byte 1048576 = 1mb
  }),
})

module.exports = {
  imageUploader,
  documentUploader,
}
